package com.hanwei.uap.acceptors.sstn.service;

import com.hanwei.uap.acceptors.api.service.MsgLogService;
import com.hanwei.uap.common.enums.sstn.FrameType;
import com.hanwei.uap.common.util.JsonUtil;
import com.hanwei.uap.model.po.MsgLog;
import io.netty.channel.Channel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.BoundListOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.net.InetSocketAddress;

@Service
public class MsgLogServiceImpl implements MsgLogService {
    private Logger log = LoggerFactory.getLogger("msgdata");
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Value(value = "${uap.qname.datatosave}")
    private String dataSaveQname;

    @Override
    public void pushToMq(Channel channel, FrameType frameType, String deviceId, String hexData, int deviceType, String serverHost, int serverPort, String tmstamp, int channelNum){
        InetSocketAddress remoteAddress = (InetSocketAddress) channel.remoteAddress();
        String clientHost = remoteAddress.getAddress().getHostAddress();
        int clientPort = remoteAddress.getPort();
        MsgLog msgLog = new MsgLog();
        msgLog.setMsgType(frameType.getMsgType());
        msgLog.setDeviceId(deviceId);
        msgLog.setDeviceType(deviceType+"");
        msgLog.setData(hexData);
        msgLog.setServerHost(serverHost);
        msgLog.setServerPort(serverPort);
        msgLog.setClientHost(clientHost);
        msgLog.setClientPort(clientPort);
        msgLog.setTmstamp(tmstamp);
        msgLog.setFlag("0");
        msgLog.setExt1(channelNum+"");
        msgLog.setExt2(frameType.toString());
        String json = JsonUtil.toJSON(msgLog);
        BoundListOperations<String, String> list = stringRedisTemplate.boundListOps(dataSaveQname);
        list.leftPush(json);
        if(log.isInfoEnabled())
            log.info(json);
    }
}
